package com.wuseguang.springcloud.service.impl;

import com.alibaba.fastjson.JSON;
import com.wuseguang.springcloud.Classcardservice.ClassCardFieldService;
import com.wuseguang.springcloud.Classcardservice.ClassCardService;
import com.wuseguang.springcloud.Filter.RequestParameterWrapper;
import com.wuseguang.springcloud.JdbcTemplate.HaiweidaCooperativeSchoolJdbc;
import com.wuseguang.springcloud.dao.jdbc.TeacherJdbc;
import com.wuseguang.springcloud.dao.repository.TeacherRepository;
import com.wuseguang.springcloud.dao.repository.TeacherRoleRepository;
import com.wuseguang.springcloud.entity.Student;
import com.wuseguang.springcloud.entity.Teacher;
import com.wuseguang.springcloud.entity.TeacherRole;
import com.wuseguang.springcloud.service.TeacherService;
import com.wuseguang.springcloud.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 教师表/教职工表 服务实现类
 * </p>
 *
 * @author
 * @since 2019-12-23
 */
@Service
public class TeacherServiceImpl implements TeacherService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private TeacherRepository teacherRepository;
    @Autowired
    private TeacherJdbc teacherJdbc;
    @Autowired
    private TeacherRoleRepository teacherRoleRepository;
    @Autowired
    private HaiweidaCooperativeSchoolJdbc haiweidaCooperativeSchoolJdbc;

    //推送接口
    @Autowired
    private ClassCardService classCardService;

    @Autowired
    private ClassCardFieldService service;

    @Override
    public Result findTeacherAll(String schoolId, String name, Integer id, Integer type, Integer roleId, Integer indexNo, Integer rows, String phone) {

        logger.info("查询教师信息 TeacherServiceImpl - > teacherServiceImpl");

        String sql = "select id,name,phone,state,sex,diploma,DATE_FORMAT(entry_time,'%Y-%m-%d') entryTime,card_number cardnumber,head_portrait headPortrait from `teacher` t where t.school_id = ? ";

        //判断如果角色id不为空
        if (!StringUtils.isEmpty(roleId)) {
            logger.info("角色不为空");
            sql += " and exists (select * from `teacher_role` tr where tr.`teacher_id`  = t.id and tr.`role_id` ='" + roleId + "')";
        }
        //判断如果classid不为空
        if (!StringUtils.isEmpty(id) && !StringUtils.isEmpty(type)) {
            logger.info("班级不为空");
            sql += " and exists (select * from `teacher_role` tr WHERE tr.`teacher_id` =t.id and tr.`pid` ='" + id + "' and tr.type=" + type + " )";
        }

        //判断如果名字不为空
        if (!StringUtils.isEmpty(phone)) {
            logger.info("名字不为空");
            sql += "  and t.`phone` LIKE '%" + phone + "%'";
        }

        //判断如果名字不为空
        if (!StringUtils.isEmpty(name)) {
            logger.info("名字不为空");
            sql += "  and t.`name` LIKE '%" + name + "%'";
        }
        logger.info("查询教师sql = {}", sql);
        //查询教师任课SQL
        String rkSql = "select tr.id teacherRoleId,concat(c.`name`,'-',r.`name` ) name from teacher_role  tr inner join `classes` c  on(tr.pid=c.id) LEFT join roles r on (tr.role_id=r.id) where tr.teacher_id =? and tr.type=3" +
                " UNION ALL " +
                "select tr.id teacherRoleId,concat(g.`name`,'-',r.`name` ) name from teacher_role  tr inner join `grade` g  on(tr.pid=g.id) LEFT join roles r on (tr.role_id=r.id) where tr.teacher_id =? and tr.type=2" +
                " UNION ALL " +
                "select tr.id teacherRoleId,concat(d.`name`,'-',r.`name` ) name from teacher_role  tr inner join `department` d  on(tr.pid=d.id) LEFT join roles r on (tr.role_id=r.id) where tr.teacher_id =? and tr.type=1";

        List<Map<String, Object>> list = teacherJdbc.queryListMap(sql, schoolId);



        //创建分页工具
        PagingTool tool = new PagingTool();
        //放入页码
        tool.setIndexNo(indexNo);
        //放入每页显示数量
        tool.setRows(rows);
        //放入角色集合
        tool.setList(list);

        List<Map<String,Object>> l = (List<Map<String,Object>>)tool.getList();
        //循环信息
        for (Map<String, Object> map : l) {
            List<Map<String, Object>> rklist = null;
            try {
                rklist = teacherJdbc.queryListMap(rkSql, map.get("id"), map.get("id"), map.get("id"));
            } catch (Exception e) {
                e.printStackTrace();
                logger.info("没有数据");
            }

            map.put("list", rklist);
        }
        //返回数据
        return new Result(new PaginationUtil<>(list.size(), rows, l, indexNo));
    }


    @Override
    public Result deleteTeacherByid(String id) {

        logger.info("删除教师信息");

     /*   logger.info("先删除教师角色");
        //循环删除
        for (int i = 0;i<teacherRoleId.length;i++){
            logger.info("删除第"+(i+1)+"个角色");
            teacherRoleRepository.deleteById(teacherRoleId[i]);
        }*/
        //删除教师信息
        teacherRepository.deleteById(Integer.valueOf(id));


        return new Result();
    }

    @Override
    public Result updateTeacherPassword(Integer id, String passWord) {

        logger.info("重置教师密码");
        //修改教师密码 默认密码123456
        String sql = "update `cloud_window`.`teacher` set `password`='" + MyDES.encryptBasedDes(passWord) + "' where `id`= ?";
        logger.info("重置密码SQL = {},修改教师的id = {}", sql, id);
        //重置教师密码
        teacherJdbc.updateByParameter(sql, id);

        return new Result();
    }

    @Override
    public Result updateAllTeacherPassword(String schoolId, String passWord) {
        logger.info("重置全校教师密码");
        //修改教师密码 默认密码123456
        String sql = "update `teacher` set `password`='" + MyDES.encryptBasedDes(passWord) + "' where `school_id`= ?";
        logger.info("重置全校教师密码sql = {},修改学校id = {}", sql, schoolId);
        //重置教师密码
        teacherJdbc.updateByParameter(sql, schoolId);

        return new Result();
    }

    @Override
    public Result teacherDetection(String schoolId, String teacher) {
        //错误信息
        List<String> errorList = new ArrayList<>();
        //错误坐标
        List<String> errorCoordinate = new ArrayList<>();

        logger.info("检测教师信息 TeacherServiceImpl -> teacherDetection");

        //查询这个学校的班级
        String sql = "select c.id,c.`name`   from `classes` c  WHERE c.`school_id`  = ?";
        logger.info("查询这个学校的班级 SQL ={}", sql);
        Map<String, Object> classMap = teacherJdbc.queryIdMap(sql, "name", "id", schoolId);
        logger.info("班级map大小 = {}", classMap.size());

        //查询这个学校的年级
        sql = "select name,id from `grade`  WHERE `school_id` =?";
        logger.info("查询这个学校的年级 SQL ={}", sql);
        Map<String, Object> gradeMap = teacherJdbc.queryIdMap(sql, "name", "id", schoolId);
        logger.info("年级map大小 = {}", gradeMap.size());

        //查询这个学校有的部门
        sql = "select name,id from `department` WHERE `school_id` IN (0,?)";
        logger.info("询这个学校有的部门 SQL ={}", sql);
        Map<String, Object> departmentMap = teacherJdbc.queryIdMap(sql, "name", "id", schoolId);
        logger.info("校有的部门map大小 = {}", departmentMap.size());

        //查询这个学校有的角色
        sql = "select name,id from `roles` WHERE `school_id` IN (0,?) and `type` = 1";
        logger.info("询这个学校有的角色 SQL ={}", sql);
        Map<String, Object> roleMap = teacherJdbc.queryIdMap(sql, "name", "id", schoolId);
        logger.info("校有的角色map大小 = {}", roleMap.size());

        //作物的x坐标
        int errorX = 0;


        //查询学校状态 0测试学校，1正式学校
        sql = "select type string from school where id = ?";
        String type = teacherJdbc.queryString(sql, schoolId);

        sql = "select phone,`id` from teacher";
        Map<String,String> phoneMap = teacherJdbc.getMap(sql,"phone","id");

        //把信息转为list集合
        List<Map<String, Object>> teacherList = (List<Map<String, Object>>) JSON.parse(teacher);
        //循环每个教师的信息
        for (Map<String, Object> map : teacherList) {
            logger.info("教师信息 = {}", map.toString());
            //教师名称
            String teacherName = map.get("name").toString().trim();
            //教师手机号码
            String teacherPhone = map.get("phone").toString().trim();
            //获取教师性别
            String teacherSex = map.get("sex").toString().trim();

            //判断如果不为男女就退出
            if (!("男".equals(teacherSex) || "女".equals(teacherSex))) {
                logger.info("性别输入错误");
                errorList.add(teacherName + "教师的性别输入错误（男/女）");
                errorCoordinate.add(errorX + ":1");
            }
            //验证结果
            int verify =  verifyPhoneTwo(Integer.valueOf(schoolId),teacherPhone,null,type,phoneMap);
            //结果
            if(verify==1){
                errorList.add("手机号码不正确");
                errorCoordinate.add(errorX + ":2");
            }else if(verify==2){
                errorList.add("手机号码已存在");
                errorCoordinate.add(errorX + ":2");
            }

            //教师角色
            List<String> teacherRole = (List<String>) JSON.parse(map.get("list").toString());
            logger.info("开始循环教师信息");
            //循环教师的角色
            for (int i = 0; i < teacherRole.size(); i++) {
                logger.info("教师部门跟角色信息 = {}", teacherRole);
                //拆分信息
                String[] classAndRole = teacherRole.get(i).split("-");
                String name = classAndRole[0].trim();
                //判断班级是否存在
                if (!(classMap.containsKey(name))) {
                    logger.info("班级不存在");
                    //判断年级是否存在
                    if (!(gradeMap.containsKey(name))) {
                        logger.info("年级不存在");
                        //判断部门是否存在
                        if (!(departmentMap.containsKey(name))) {
                            logger.info("部门不存在");
                            errorList.add(classAndRole[0] + "不存在");
                            errorCoordinate.add(errorX + ":3");
                        }
                    }
                }
                //判断角色是否存在
                if (classAndRole.length > 1 && !(roleMap.containsKey(classAndRole[1].trim()))) {
                    logger.info("角色不存在");
                    errorList.add(classAndRole[1] + "角色不存在");
                    errorCoordinate.add(errorX + ":3");
                }
            }
            errorX++;
        }

        //判断错误信息大于0
        if (errorList.size() > 0) {
            Map<String, Object> map = new HashMap<>();
            map.put("errorList", errorList);
            map.put("errorCoordinate", errorCoordinate);
            logger.info("有错误信息");
            return new Result(CodeUtil.RETRIEVE_AND_REPORT_ERRORS, map);
        }
        return new Result();
    }

    @Transactional
    @Override
    public Result batchAdditionTeacher(String schoolId, String teacher) {

        logger.info("添加教师信息 TeacherServiceImpl -> batchAdditionTeacher");

        //查询这个学校的班级
        String sql = "select c.id,c.`name`   from `classes` c WHERE c.`school_id`  = ?";
        logger.info("查询这个学校的班级 SQL ={}", sql);
        Map<String, Object> classMap = teacherJdbc.queryIdMap(sql, "name", "id", schoolId);
        logger.info("班级map大小 = {}", classMap.size());

        //查询这个学校的年级
        sql = "select name,id from `grade`  WHERE `school_id` =?";
        logger.info("查询这个学校的年级 SQL ={}", sql);
        Map<String, Object> gradeMap = teacherJdbc.queryIdMap(sql, "name", "id", schoolId);
        logger.info("年级map大小 = {}", gradeMap.size());

        //查询这个学校有的部门
        sql = "select name,id from `department` WHERE `school_id` IN (0,?)";
        logger.info("询这个学校有的部门 SQL ={}", sql);
        Map<String, Object> departmentMap = teacherJdbc.queryIdMap(sql, "name", "id", schoolId);
        logger.info("校有的部门map大小 = {}", departmentMap.size());

        //查询这个学校有的角色
        sql = "select name,id from `roles` WHERE `school_id` IN (0,?) and `type` = 1";
        logger.info("询这个学校有的角色 SQL ={}", sql);
        Map<String, Object> roleMap = teacherJdbc.queryIdMap(sql, "name", "id", schoolId);
        logger.info("校有的角色map大小 = {}", roleMap.size());

        //创建教师角色
        List<TeacherRole> trList = new ArrayList<TeacherRole>();
        //海威达同步教师信息
        List<Teacher> hwdlist = new ArrayList<>();
        //把信息转为list集合
        List<Map<String, Object>> teacherList = (List<Map<String, Object>>) JSON.parse(teacher);
        //循环每个教师的信息
        for (Map<String, Object> map : teacherList) {
            logger.info("教师信息 = {}", map.toString());
            //教师名称
            String teacherName = map.get("name").toString();
            //教师手机号码
            String teacherPhone = map.get("phone").toString();
            //获取教师性别
            String teacherSex = map.get("sex").toString();

            //创建教师集合
            Teacher t = new Teacher();
            //非管理
            t.setAdmin(1);
            //教师名称
            t.setName(teacherName);
            //教师手机号码
            t.setPhone(teacherPhone);
            //密码
            t.setPassword("x16YjoF1LNE=");
            //性别
            t.setSex("男".equals(teacherSex) ? 0 : 1);
            //是否在职
            t.setState(0);
            //入职时间
            t.setEntryTime(new Date());
            //学校id
            t.setSchoolId(Integer.valueOf(schoolId));
            //头像
            t.setHeadPortrait("男".equals(teacherSex) ? "https://oss.yuguozhijia.online/headPortrait/教师头像（男）.png" : "https://oss.yuguozhijia.online/headPortrait/教师头像（女）.png");
            //教师id
            Integer teacherId = teacherRepository.save(t).getId();
            //添加
            hwdlist.add(t);


            //教师角色
            List<String> teacherRole = (List<String>) JSON.parse(map.get("list").toString());

            logger.info("开始循环教师信息");
            //循环教师的角色
            for (int i = 0; i < teacherRole.size(); i++) {
                logger.info("教师部门跟角色信息 = {}", teacherRole);
                //拆分信息
                String[] classAndRole = teacherRole.get(i).split("-");

                //判断长度小于二
                if (classAndRole.length > 2) {
                    //小于二没有部门
                    continue;
                }
                //创建教师角色集合
                TeacherRole tr = new TeacherRole();


                //判断是否是班级
                if (classMap.containsKey(classAndRole[0].trim())) {
                    //上级id
                    tr.setPid(Integer.valueOf(classMap.get(classAndRole[0].trim()).toString()));
                    //班级
                    tr.setType(3);
                    //判断是否是班主任
                    if ("班主任".equals(classAndRole[1].trim())) {
                        sql = "update `classes` set `class_teacher_id`=? where `id`=? ";
                        Integer integer = Integer.valueOf(classMap.get(classAndRole[0].trim()).toString());
                        teacherJdbc.updateByParameter(sql, teacherId, integer);

                        //修改心跳并推送
                        service.classesAndCards(integer, "classflag", "1");
                        classCardService.classesAndCards(integer);
                    }

                    //判断是否是年级
                } else if (gradeMap.containsKey(classAndRole[0].trim())) {
                    //上级id
                    tr.setPid(Integer.valueOf(gradeMap.get(classAndRole[0].trim()).toString()));
                    //年级
                    tr.setType(2);
                    //判断是否是部门
                } else if (departmentMap.containsKey(classAndRole[0].trim())) {
                    //上级id
                    tr.setPid(Integer.valueOf(departmentMap.get(classAndRole[0].trim()).toString()));
                    //部门
                    tr.setType(1);
                }
                //教师id
                tr.setTeacherId(teacherId);
                //角色id
                tr.setRoleId(Integer.valueOf(roleMap.get(classAndRole[1].trim()).toString()));
                //学校id
                tr.setSchoolId(Integer.valueOf(schoolId));
                //添加到集合
                trList.add(tr);
            }
        }
        teacherRoleRepository.saveAll(trList);

        try {
            haiweidaCooperativeSchoolJdbc.haiweidaTeacher(hwdlist);
        }catch (Exception e){
            logger.info("海威达教师同步失败");
        }

        return new Result();
    }

    @Override
    public Result addTeacher(String schoolId, Teacher t) {

        //查询这个学校的班级
        String sql = "select c.id,c.`name`    from `classes` c WHERE c.`school_id`  = ?";
        logger.info("查询这个学校的班级 SQL ={}", sql);
        Map<String, Object> classMap = teacherJdbc.queryIdMap(sql, "name", "id", schoolId);
        logger.info("班级map大小 = {}", classMap.size());

        //查询这个学校的年级
        sql = "select name,id from `grade`  WHERE `school_id` =?";
        logger.info("查询这个学校的年级 SQL ={}", sql);
        Map<String, Object> gradeMap = teacherJdbc.queryIdMap(sql, "name", "id", schoolId);
        logger.info("年级map大小 = {}", gradeMap.size());

        //查询这个学校有的部门
        sql = "select name,id from `department` WHERE `school_id` IN (0,?)";
        logger.info("询这个学校有的部门 SQL ={}", sql);
        Map<String, Object> departmentMap = teacherJdbc.queryIdMap(sql, "name", "id", schoolId);
        logger.info("校有的部门map大小 = {}", departmentMap.size());

        //查询这个学校有的角色
        sql = "select name,id from `roles` WHERE `school_id` IN (0,?) and `type` = 1";
        logger.info("询这个学校有的角色 SQL ={}", sql);
        Map<String, Object> roleMap = teacherJdbc.queryIdMap(sql, "name", "id", schoolId);
        logger.info("校有的角色map大小 = {}", roleMap.size());

        //验证结果
        int verify =  verifyPhone(Integer.valueOf(schoolId),t.getPhone(),null);
        if(verify==1){
            return new Result(CodeUtil.PLEASE_ENTER_THE_CORRECT_MOBILE_PHONE_NUMBER);
        }else if(verify==2){
            return new Result(CodeUtil.MOBILE_NUMBER_ALREADY_EXISTS);
        }

        //非管理
        t.setAdmin(1);
        //密码
        t.setPassword("x16YjoF1LNE=");
        //是否在职
        t.setState(0);
        //学校id
        t.setSchoolId(Integer.valueOf(schoolId));

        //判断头像是否为空
        if (StringUtils.isEmpty(t.getHeadPortrait())) {
            //头像
            t.setHeadPortrait("0".equals(t.getSex().toString()) ? "https://oss.yuguozhijia.online/headPortrait/教师头像（男）.png" : "https://oss.yuguozhijia.online/headPortrait/教师头像（女）.png");
        }


        //教师id
        Integer teacherId = teacherRepository.save(t).getId();
        try {
            List<Teacher> hwdlist = new ArrayList<>();
            hwdlist.add(t);
            haiweidaCooperativeSchoolJdbc.haiweidaTeacher(hwdlist);
        }catch (Exception e){
            logger.info("海威达教师同步失败");
        }

        //创建教师角色
        List<TeacherRole> trList = new ArrayList<TeacherRole>();

        //教师角色
        List<String> teacherRole = (List<String>) JSON.parse(t.getList());

        logger.info("开始循环教师信息");
        //循环教师的角色
        for (int i = 0; i < teacherRole.size(); i++) {
            logger.info("教师部门跟角色信息 = {}", teacherRole);
            //拆分信息
            String[] classAndRole = teacherRole.get(i).split("-");

            //判断长度小于二
            if (classAndRole.length > 2) {
                //小于二没有部门
                continue;
            }
            //创建教师角色集合
            TeacherRole tr = new TeacherRole();


            //判断是否是班级
            if (classMap.containsKey(classAndRole[0].trim())) {
                //上级id
                tr.setPid(Integer.valueOf(classMap.get(classAndRole[0].trim()).toString()));
                //班级
                tr.setType(3);
                //判断是否是班主任
                if ("班主任".equals(classAndRole[1].trim())) {
                    sql = "update `classes` set `class_teacher_id`=? where `id`=? ";
                    Integer integer = Integer.valueOf(classMap.get(classAndRole[0].trim()).toString());
                    teacherJdbc.updateByParameter(sql, teacherId, integer);
                    //修改心跳并推送
                    service.classesAndCards(integer, "classflag", "1");
                    classCardService.classesAndCards(integer);
                }

                //判断是否是年级
            } else if (gradeMap.containsKey(classAndRole[0].trim())) {
                //上级id
                tr.setPid(Integer.valueOf(gradeMap.get(classAndRole[0].trim()).toString()));
                //年级
                tr.setType(2);
                //判断是否是部门
            } else if (departmentMap.containsKey(classAndRole[0].trim())) {
                //上级id
                tr.setPid(Integer.valueOf(departmentMap.get(classAndRole[0].trim()).toString()));
                //部门
                tr.setType(1);
            }
            //教师id
            tr.setTeacherId(teacherId);
            //学校id
            tr.setSchoolId(Integer.valueOf(schoolId));
            //角色id
            tr.setRoleId(Integer.valueOf(roleMap.get(classAndRole[1].trim()).toString()));
            //添加到集合
            trList.add(tr);
        }

        teacherRoleRepository.saveAll(trList);
        return new Result();
    }

    @Override
    public Result updateTeacher(Teacher teacher) {


        //查询这个学校的班级
        String sql = "select c.id,c.`name`  name  from `classes` c WHERE c.`school_id`  = ?";
        logger.info("查询这个学校的班级 SQL ={}", sql);
        Map<String, Object> classMap = teacherJdbc.queryIdMap(sql, "name", "id", teacher.getSchoolId());
        logger.info("班级map大小 = {}", classMap.size());

        //查询这个学校的年级
        sql = "select name,id from `grade`  WHERE `school_id` =?";
        logger.info("查询这个学校的年级 SQL ={}", sql);
        Map<String, Object> gradeMap = teacherJdbc.queryIdMap(sql, "name", "id", teacher.getSchoolId());
        logger.info("年级map大小 = {}", gradeMap.size());

        //查询这个学校有的部门
        sql = "select name,id from `department` WHERE `school_id` IN (0,?)";
        logger.info("询这个学校有的部门 SQL ={}", sql);
        Map<String, Object> departmentMap = teacherJdbc.queryIdMap(sql, "name", "id", teacher.getSchoolId());
        logger.info("校有的部门map大小 = {}", departmentMap.size());

        //查询这个学校有的角色
        sql = "select name,id from `roles` WHERE `school_id` IN (0,?) and `type` = 1";
        logger.info("询这个学校有的角色 SQL ={}", sql);
        Map<String, Object> roleMap = teacherJdbc.queryIdMap(sql, "name", "id", teacher.getSchoolId());
        logger.info("校有的角色map大小 = {}", roleMap.size());

        //先删除原来的角色
        sql = "delete from `teacher_role` where `teacher_id`= ?";
        teacherJdbc.updateByParameter(sql, teacher.getId());

        //验证结果
        int verify =  verifyPhone(teacher.getSchoolId(),teacher.getPhone(),teacher.getId());
        if(verify==1){
            return new Result(CodeUtil.PLEASE_ENTER_THE_CORRECT_MOBILE_PHONE_NUMBER);
        }else if(verify==2){
            return new Result(CodeUtil.MOBILE_NUMBER_ALREADY_EXISTS);
        }

        //先查询出原来的数据
        Optional<Teacher> optional = teacherRepository.findById(teacher.getId());

        //判断头像是否为空
        if (StringUtils.isEmpty(teacher.getHeadPortrait())) {
            //头像
            teacher.setHeadPortrait(teacher.getSex() == 0 ? "https://oss.yuguozhijia.online/headPortrait/教师头像（男）.png" : "https://oss.yuguozhijia.online/headPortrait/教师头像（女）.png");
        }
        //创建修改工具
        UpdateTool.copyNullProperties(optional.get(), teacher);
        teacherRepository.save(teacher);

        try {
            List<Teacher> hwdlist = new ArrayList<>();
            hwdlist.add(teacher);
            haiweidaCooperativeSchoolJdbc.haiweidaTeacher(hwdlist);
        }catch (Exception e){
            logger.info("海威达教师同步失败");
        }

        //教师名字可能改了需要修改课表的教师名字
        sql = "UPDATE `timetable` SET `teacher_name` = ? WHERE teacher_id=?";
        teacherJdbc.updateByParameter(sql, teacher.getName(), teacher.getId());


        //创建教师角色
        List<TeacherRole> trList = new ArrayList<TeacherRole>();

        sql = "UPDATE `classes` SET `class_teacher_id` = null WHERE `class_teacher_id` = ?";
        teacherJdbc.updateByParameter(sql, teacher.getId());
        service.classesAndCards(teacher.getId(), "classflag", "1");
        classCardService.classesAndCards(teacher.getId());
        //教师角色
        List<String> teacherRole = (List<String>) JSON.parse(teacher.getList());

        logger.info("开始循环教师信息");
        //循环教师的角色
        for (int i = 0; i < teacherRole.size(); i++) {
            logger.info("教师部门跟角色信息 = {}", teacherRole);
            //拆分信息
            String[] classAndRole = teacherRole.get(i).split("-");

            //创建教师角色集合
            TeacherRole tr = new TeacherRole();


            //判断是否是班级
            if (classMap.containsKey(classAndRole[0])) {
                //上级id
                tr.setPid(Integer.valueOf(classMap.get(classAndRole[0]).toString()));
                //班级
                tr.setType(3);
                //判断是否是班主任，如果为班主任要把这个教师添加到班级
                if ("班主任".equals(classAndRole[1])) {
                    sql = "update `classes` set `class_teacher_id`=? where `id`=? ";
                    Integer integer = Integer.valueOf(classMap.get(classAndRole[0]).toString());
                    teacherJdbc.updateByParameter(sql, teacher.getId(), integer);
                    sql = " DELETE FROM teacher_role WHERE type=3 AND pid=? AND role_id=2";
                    teacherJdbc.updateByParameter(sql, integer);
                    service.classesAndCards(integer, "classflag", "1");
                    classCardService.classesAndCards(integer);
                }

                //判断是否是年级
            } else if (gradeMap.containsKey(classAndRole[0])) {
                //上级id
                tr.setPid(Integer.valueOf(gradeMap.get(classAndRole[0]).toString()));
                //年级
                tr.setType(2);
                //判断是否是部门
            } else if (departmentMap.containsKey(classAndRole[0])) {
                //上级id
                tr.setPid(Integer.valueOf(departmentMap.get(classAndRole[0]).toString()));
                //部门
                tr.setType(1);
            }
            //教师id
            tr.setTeacherId(teacher.getId());
            //学校id
            tr.setSchoolId(teacher.getSchoolId());
            //角色id
            tr.setRoleId(Integer.valueOf(roleMap.get(classAndRole[1]).toString()));
            //添加到集合
            trList.add(tr);
        }

        teacherRoleRepository.saveAll(trList);
        return new Result();
    }

    @Override
    public void exportTeacherTemplate(RequestParameterWrapper request, HttpServletResponse response) {
        logger.info("导出教师模板");
        ExeclUtils.downloadExcelOrdinaryTemplate(request, response, "template/teacherTemplates.xls", "教师导入模板.xls");
    }

    @Override
    public void exportTeacher(RequestParameterWrapper request, HttpServletResponse response) {

        //学校id
        String schoolId = request.getParam("schoolId");

        String sql = "select name ,case sex when '0' then '男' else '女' end as sex ,phone,card_number,diploma,DATE_FORMAT(entry_time,'%Y-%m-%d') entry_time from teacher where school_id = ?";
        //查询教师信息
        List<Map<String, Object>> list = teacherJdbc.queryListMap(sql, schoolId);

        //key
        String[] key = new String[]{"姓名", "性别", "手机号码", "卡号", "学历", "入职时间"};
        //values
        String[] value = new String[]{"name", "sex", "phone", "card_number", "diploma", "entry_time"};

        try {
            ExeclUtils.downloadExcelMapTemplate(response, list, key, value, "教师信息");
        } catch (IOException e) {
            logger.info("教师导出错误,e", e);
        }
    }

    @Override
    public Result findShcoolTeacher(String schoolId) {
        //查询学校教师
        String sql = "select id,`name` from teacher where school_id = ?";
        List<Map<String,Object>> list = teacherJdbc.queryListMap(sql,schoolId);
        return new Result(list);
    }


    public int verifyPhoneTwo(Integer schoolId,String phone,Integer id,String type,Map<String,String> phoneMap){


        //验证手机号码
        //如果为测试学校
        if ("0".equals(type)) {
            //测试账号必须为11位数
            if (phone.length() != 11) {
                //请输入正确的手机号码
                return 1;
            }
        } else {
            //2020手机号码验证
            String regex = "^((13[0-9])|(14[0|5|6|7|9])|(15[0-3])|(15[5-9])|(16[6|7])|(17[2|3|5|6|7|8])|(18[0-9])|(19[1|8|9]))\\d{8}$";
            if (phone.length() != 11) {
                System.out.println("手机号应为11位数");
                return 1;
            }
//            else {
//                Pattern p = Pattern.compile(regex);
//                Matcher m = p.matcher(phone);
//                boolean isMatch = m.matches();
//                if (!isMatch) {
//                    //请输入正确的手机号码
//                    return 1;
//
//                }
//            }
        }


        //判断手机号码是否已经存在
        if(!StringUtils.isEmpty(id)&&phoneMap.get(phone)!=null&&!phoneMap.get(phone).equals(id+"")){
            //号码已存在
            return 2;
        }
        //无误
        return 0;
    }


    /**
     * 验证手机号码
     * @param schoolId
     * @param phone
     * @return
     */
    public int verifyPhone(Integer schoolId,String phone,Integer id){
        //查询学校状态 0测试学校，1正式学校
        String sql = "select type string from school where id = ?";
        String type = teacherJdbc.queryString(sql, schoolId);

        //验证手机号码
        //如果为测试学校
        if ("0".equals(type)) {
            //测试账号必须为11位数
            if (phone.length() != 11) {
                //请输入正确的手机号码
                return 1;
            }
        } else {
            //2020手机号码验证
            String regex = "^((13[0-9])|(14[0|5|6|7|9])|(15[0-3])|(15[5-9])|(16[6|7])|(17[2|3|5|6|7|8])|(18[0-9])|(19[1|8|9]))\\d{8}$";
            if (phone.length() != 11) {
                System.out.println("手机号应为11位数");
                return 1;
            }
//            else {
//                Pattern p = Pattern.compile(regex);
//                Matcher m = p.matcher(phone);
//                boolean isMatch = m.matches();
//                if (!isMatch) {
//                    //请输入正确的手机号码
//                    return 1;
//
//                }
//            }
        }

        sql = "select phone,`id` from teacher";
        Map<String,String> phoneMap = teacherJdbc.getMap(sql,"phone","id");
        //判断手机号码是否已经存在
        if(!StringUtils.isEmpty(id)&&phoneMap.get(phone)!=null&&!phoneMap.get(phone).equals(id+"")){
            //号码已存在
            return 2;
        }
        //无误
        return 0;
    }
}